package cn.virens.web.controller.manage.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hutool.core.util.StrUtil;
import cn.virens.common.RequestUtil;
import cn.virens.common.StringUtil;
import cn.virens.database.mysql.model.sys.SysUser;
import cn.virens.database.service.sys.SysUserService;
import cn.virens.web.common.BaseUserController;

@RequestMapping("/manage/base")
@Controller("ManageBasePageContorller")
public class BasePageContorller extends BaseUserController {
	private @Autowired SysUserService mSysUserService;

	public BasePageContorller() {
		super("/manage/base");
	}

	@RequestMapping("user/view.jspx")
	public String userView(HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("user", mSysUserService.getUser(getAccount(request)));

		return returnUrl("user/view");
	}

	@RequestMapping("user/edit.jspx")
	public String userEdit(HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("user", mSysUserService.getUser(getAccount(request)));

		return returnUrl("user/edit");
	}

	@ResponseBody
	@RequestMapping("user/edit/save.json")
	public Model userEditSave(HttpServletRequest request, HttpServletResponse response, Model model) {
		SysUser user = new SysUser();
		user.setAvatar(RequestUtil.getValueStr(request, "avatar"));
		user.setPhone(RequestUtil.getValueStr(request, "phone"));
		user.setEmail(RequestUtil.getValueStr(request, "email"));
		user.setName(RequestUtil.getValueStr(request, "name"));
		user.setQq(RequestUtil.getValueStr(request, "qq"));
		user.setAccount(getAccount(request));

		logParam(request, "修改当前用户资料");

		if (mSysUserService.update(user) != null) {
			return renderSuccess(model, "保存成功");
		} else {
			return renderFail(model, "保存失败");
		}
	}

	@RequestMapping("user/pwd.jspx")
	public String userPwd(HttpServletRequest request, HttpServletResponse response, Model model) {
		return returnUrl("user/pwd");
	}

	@ResponseBody
	@RequestMapping("user/pwd/save.json")
	public Model userPwdSave(HttpServletRequest request, HttpServletResponse response, Model model) {
		String passwordRetry = RequestUtil.getValueStr(request, "password_retry");
		String password = RequestUtil.getValueStr(request, "password");

		if (StrUtil.equals(password, passwordRetry)) {
			SysUser user = new SysUser();
			user.setPassword(StringUtil.md5(password));
			user.setAccount(getAccount(request));

			logParam(request, "修改当前用户密码");

			if (mSysUserService.update(user) != null) {
				return renderSuccess(model, "修改成功");
			} else {
				return renderFail(model, "修改失败");
			}
		} else {
			return renderFail(model, "两次密码不同");
		}
	}
}
